package cn.com.ahao.gateway.web;

import cn.com.ahao.gateway.context.GatewayContextHolder;
import cn.com.ahao.gateway.service.IApiCodeService;
import cn.com.ahao.gateway.vo.dvo.ApiCodeDVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class GatewayController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IApiCodeService apiCodeService;

    @GetMapping("/api/{apiCode}")
    public String entry(@PathVariable("apiCode") String apiCode) {
        ApiCodeDVO apiCodeDVO = apiCodeService.getByApiCode(apiCode);
        if (apiCodeDVO == null) {
            throw new RuntimeException("unknow api");
        }
        String url = "http://" + apiCodeDVO.getSystemCode() + apiCodeDVO.getUrl();
        logger.info("gateway request url: {}", url);
        return restTemplate.getForObject(url, String.class);
    }

    @PostMapping("/api/{apiCode}")
    public Map entry(@PathVariable("apiCode") String apiCode, HttpServletRequest request, @RequestBody Map body) {
        ApiCodeDVO apiCodeDVO = apiCodeService.getByApiCode(apiCode);
        if (apiCodeDVO == null) {
            throw new RuntimeException("unknow api");
        }
        String url = "http://" + apiCodeDVO.getSystemCode() + apiCodeDVO.getUrl();
        logger.info("gateway request url: {}", url);

        // 1. 封装Header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("traceId", GatewayContextHolder.getContext().getTraceId());
        headers.set("startTime", GatewayContextHolder.getContext().getStartTime().toString());
        headers.set("userAgent", request.getHeader("user-agent"));
        headers.set("refer", request.getHeader("refer"));
        // 2.封装body参数，转换为json字符串
        String httpEntityBody = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            httpEntityBody = objectMapper.writeValueAsString(body);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException("object write error");
        }
        HttpEntity<String> httpEntity = new HttpEntity<>(httpEntityBody, headers);
        // 3.调用微服务
        ResponseEntity<HashMap> responseEntity = restTemplate.postForEntity(url, httpEntity, HashMap.class);
        // 4.获取返回的消息
        return responseEntity.getBody();
    }

}
